<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class GongGongController extends Controller
{
	/**
	 * 图片上传
	 *
	 * Date: 2018/2/28
	 * @author Eric
	 * @param Request $request
	 * @return \Illuminate\Http\JsonResponse
	 */
    public function imageUpload(Request $request)
    {
        // QQ20180215-113434@1x.png
        if ($request->file('file')->isValid()){
            $file = $request->file('file');
//        return $file->getClientOriginalName();
            $file_path = 'public/' . date('m') . '/' . date('d');
            $path = $file->store($file_path);
            return $this->success(['url'=>Storage::url($path)]);
        }else{
            return $this->failed("上传错误");
        }

    }

    public function Upload(Request $request){

        if ($request->file('file')->isValid()){
            $file = $request->file('file');
            $file_path = 'public/' . date('m') . '/' . date('d');
            $path = $file->store($file_path);
            return $this->success(['url'=>Storage::url($path)]);
        }else{
            return $this->failed("上传错误");
        }
    }

	/**
	 * 图片删除
	 *
	 * Date: 2018/2/28
	 * @author Eric
	 * @param Request $request
	 * @return \Illuminate\Http\JsonResponse
	 */
    public function imageDelete(Request $request)
    {
        $path = $request->input('path','');

        if($path){
            Storage::disk('public')->delete(str_replace('/storage', '', $path));

            return $this->success(['message' => '删除成功', 'path' => $path]);
        }else{
            $this->failed('删除失败');
        }
    }

    /**
     *
     *
     * @author Eric
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function base64_imageUpload(Request $request)
    {
        $image = $request->base64Img;

        $imageName = "25220_".date("His",time())."_".rand(1111,9999).'.jpg';

        if (strstr($image,",")){
            $image = explode(',',$image);
            $image = $image[1];
        }

        $path = "storage/app/public/".date("m");
        if (!is_dir($path)){ //判断目录是否存在 不存在就创建
            mkdir($path,0777,true);
        }
        $imageSrc=  $path."/". $imageName;  //图片名字

        $r = file_put_contents($imageSrc, base64_decode($image));//返回的是字节数

        if (!$r) {
            $this->failed('删除失败');
        }else{
            return $this->success(['message' => '上传成功', 'path' => $imageSrc]);
        }

    }
}
